namespace Lotto.Domain.Entitys.UserAndPermission;

public class User : EntityBase
{
    public string UserName { get; protected set; } = null!;
    public string? Phone { get; protected set; }
    public string PasswordHash { get; protected set; } = null!;
    public string PasswordSalt { get; protected set; } = null!;
    public string? NickName { get; protected set; }
    public string? AvatarUrl { get; protected set; }
    public UserStatus Status { get; protected set; } = UserStatus.Pending;
    public DateTime RegisterTime { get; protected set; } = DateTime.UtcNow;
    public string? RegisterIP { get; protected set; }

    public User() { }

    private User(string userName, string password, string? phone = null, string? registerIP = null)
    {
        UserName = userName;
        Phone = phone;
        PasswordSalt = GenerateSalt();
        PasswordHash = HashPassword(password, PasswordSalt);
        Status = UserStatus.Pending;
        RegisterIP = registerIP;
    }

    /// <summary>
    /// 工厂方法，创建用户
    /// </summary>
    public static User Create(string userName, string password, string? phone = null, string? registerIP = null)
    {
        return new User(userName, password, phone, registerIP);
    }

    /// <summary>
    /// 验证密码
    /// </summary>
    public bool VerifyPassword(string password)
    {
        var hash = HashPassword(password, PasswordSalt);
        return hash == PasswordHash;
    }

    /// <summary>
    /// 设置用户状态
    /// </summary>
    public void SetStatus(UserStatus status)
    {
        Status = status;
    }

    /// <summary>
    /// 更新手机号
    /// </summary>
    public void SetPhone(string phone)
    {
        Phone = phone;
    }

    /// <summary>
    /// 更新昵称
    /// </summary>
    public void SetNickName(string? nickName)
    {
        NickName = nickName;
    }

    /// <summary>
    /// 更新头像地址
    /// </summary>
    public void SetAvatarUrl(string? avatarUrl)
    {
        AvatarUrl = avatarUrl;
    }

    /// <summary>
    /// 生成密码盐
    /// </summary>
    private static string GenerateSalt()
    {
        var bytes = new byte[16];
        using var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
        rng.GetBytes(bytes);
        return Convert.ToBase64String(bytes);
    }

    /// <summary>
    /// 密码加密
    /// </summary>
    private static string HashPassword(string password, string salt)
    {
        var combined = System.Text.Encoding.UTF8.GetBytes(password + salt);
        var hash = System.Security.Cryptography.SHA256.HashData(combined);
        return Convert.ToBase64String(hash);
    }
}

public enum UserStatus
{
    Pending,    // 待审核
    Active,     // 已授权
    Disabled,   // 禁用
    Frozen,     // 冻结
    Banned      // 封禁
}

